import { login as userLogin, logout as userLogout } from '@/api/sys/user/oauth2'
import { getInfo as getUserInfo } from '@/api/sys/user/user'
import { getRefreshToken, getToken, removeRefreshToken, removeToken, setToken as saveToken } from '@/utils/auth'
import { defineStore } from 'pinia'
import { resetRouter } from '@/router'
import { store } from '@/stores'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { isNull } from '@/utils'

export const userStore = defineStore('user', () => {
  const userInfo = ref()
  const token = ref(getToken())
  const refreshToken = ref(getRefreshToken())
  const roles = ref([])

  function setToken(tokenParam) {
    token.value = tokenParam
    saveToken(tokenParam)
  }

  // user login
  function login(userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      userLogin(username.trim(), password).then(response => {
        const data = response.data
        if (!response.data.success) {
          ElMessage.error(response.data.msg)
        }
        setToken(data.data.token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  }

  // get user info
  function getInfo() {
    return new Promise((resolve, reject) => {
      getUserInfo(token).then(response => {
        const data = response.data.data

        if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          roles.value = data.roles
        } else {
          reject(response)
        }
        userInfo.value = data
        if (!isNull(userInfo.value.portrait)) {
          try {
            const portrait = JSON.parse(userInfo.value.portrait)
            userInfo.value.portrait = portrait[0].url
          } catch {
            resolve(data)
            return
          }
        }
        resolve(data)
      }).catch(error => {
        store.userStore.logout().then(() => {
          // this.$router.push(`/login`)
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
        reject(error)
      })
    })
  }

  // user logout
  function logout() {
    return new Promise((resolve, reject) => {
      userLogout(token).then(() => {
        token.value = ''
        refreshToken.value = ''
        userInfo.value = {}
        roles.value = []
        removeToken()
        removeRefreshToken()
        resetRouter()
        store.permissionStore.resetPermissionsAndRoute()
        store.tagsViewStore.delAllViews()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }

  return { userInfo, token, refreshToken, roles, login, getInfo, logout, setToken }
})
